<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>C++ Tutorial: Type Cast Operators</title>
  <meta
 content="C++ Tutorial: Type Cast Operators"
 name="description" />
  <meta
 content="C++ Tutorial, Type Cast Operators, Dynamic_cast, static_cast, reinterpret_cast, const_cast"
 name="keywords" />
  <meta http-equiv="Content-Type"
 content="text/html; charset=ISO-8859-1" />
  <link type="text/css" rel="stylesheet" href="../images/bogostyleWidePre.css" />
</head>
<body>
<div id="page" align="center">
<div id="content" style="width: 800px;">
<div id="logo">
<div class="whitetitle" style="margin-top: 70px;">bogotobogo </div>
</div>
<div id="topheader">
<div class="headerbodytext" align="left"><br />
<strong>Bogotobogo</strong><br />
contact@bogotobogo.com </div>
<div class="smallgraytext" id="toplinks"><a href="../index.html">Home</a>
| <a href="../sitemap.html">Sitemap</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="menu">
<div class="smallwhitetext" style="padding: 9px;" align="right"><a
 href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">Products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="submenu">
<div class="smallgraytext" style="padding: 9px;" align="right">
<a href="../gif.html">Gif</a> 
|<a href="../java_applet.html">JavaApplet/Web Start</a>
| <a href="../flash.html">Flash</a>
| <a href="../shockwave.html">ShockWave</a>
| <a href="../svg.html">SVG</a>
| <a href="../iPhone.html">iPhone/iPad</a>
| <a href="../android.html">Android</a>
| <a href="../OnHTML5.html">HTML5</a>
| <a href="../Algorithms/algorithms.html">Algorithms</a>
| <a href="../News/NewsMain.html">News</a>
| <a href="../cplusplus/cpptut.html">C++</a>
| <a href="../Java/tutorial/on_java.html">Java</a>
| <a href="../php/phptut.html">PHP</a>
| <a href="../DesignPatterns/introduction.html">Design Patterns</a>
| <a href="../python/pytut.html">Python</a>
| <a href="../CSharp/.netframework.html">C#</a>
| <a href="../forums.html">Forums</a> 
| <a href="../VisualBasicSQL/introduction.html">Visual Basic</a>
</div>
</div>

<div id="contenttext">
<br />
<!-- Use of this code assumes agreement with the Google Custom Search Terms of Service. -->
<!-- The terms of service are available at http://www.google.com/cse/docs/tos.html -->
<form name="cse" id="searchbox_demo" action="http://www.google.com/cse">
  <input type="hidden" name="cref" value="" />
  <input type="hidden" name="ie" value="utf-8" />
  <input type="hidden" name="hl" value="" />
  <input name="q" type="text" size="40" />
  <input type="submit" name="sa" value="Search" />
</form>
<script type="text/javascript" src="http://www.google.com/cse/tools/onthefly?form=searchbox_demo&lang="></script>


<br />
<div style="padding: 10px;"><span class="titletext">C++ Tutorial - Type Cast Operators</span></div>

<div id="bookmarkshare">
<script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script>
<a class="addthis_button" href="http://www.addthis.com/bookmark.php?v=250&amp;username=khhong7"><img src="http://s7.addthis.com/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=khhong7"></script>
</div>


<img src="../images/cplusplus/cpp_logo.jpg" alt="cplusplus logo"/>

<div class="bodytext" style="padding: 12px;" align="justify"> 
<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors (Function Objects)</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL)</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="stl3_iterators.html">Standard Template Library (STL) III - Iterators</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>
</div>

<br /><br />
<img src="images/typecast/SorakDong.png" alt="SorakDong"/>
<br /><br />


<br />
<div class="bodytext" style="padding: 12px;" align="justify">
<div class="subtitle" id="typeconversions">Type-Conversion Operators</div>
<p>Here is the list of <strong>type-conversions</strong>.</p>
<ul>
    <li><p><strong>a = dynamic_cast&lt;T*&gt;(p)</strong> <br />
     Try to convert <strong>p</strong> into a <strong>T*</strong>. It may return <strong>0</strong></p>
    </li>
     <li><p><strong>a = dynamic_cast&lt;T&&gt;(*p)</strong> <br />
     Try to convert <strong>*p</strong> into a <strong>T&</strong>. It may throw <strong>bad_cast</strong></p>
    </li> 
     <li><p><strong>a = static_cast&lt;T&gt;(p)</strong> <br />
     Convert <strong>p</strong> into a <strong>T</strong> if a <strong>T</strong> 
can be conterted into <strong>p</strong>'s type.</p>
    </li>   
     <li><p><strong>a = reinterpret_cast&lt;T&gt;(p)</strong> <br />
     Convert <strong>p</strong> into a <strong>T</strong> represented by the same bit pattern.</p>
    </li>  
     <li><p><strong>a =const_cast&lt;T&gt;(p)</strong> <br />
     Convert <strong>p</strong> into a <strong>T</strong> by adding or subtracting <strong>const</strong>.</p>
    </li>  
     <li><p><strong>a = (T)v</strong> <br />
     C-style cast.</p>
    </li> 
     <li><p><strong>a = T(v)</strong> <br />
     Functional cast.</p>
    </li> 
</ul>
<br />
<br />
<div class="subtitle" id="const_cast">const_cast</div>
<p><strong>const_cast</strong> is typically used to cast away the constness of objects. It is the only C++ style that can do this.</p>
<p>The syntax is:</p>
<pre>
const_cast &lt; type-name &gt; (expression)
</pre>
<p>The reason for this operator is that we may have a need for a value that is constant most of the time but that can be changed occasionally. In such a case, we can declare the value as <strong>const</strong> and use <strong>const_cast</strong> when we need to alter the value.</p>
<p>Here is a simple example:</p>
<pre>
#include &lt;iostream&gt;
#include &lt;cstring&gt;
using namespace std;
int main () {
  string str("A123456789");
  const char *cstr = str.c_str();
  <font color="red">char *nonconst_cstr  = const_cast&lt;char *&gt; (cstr) ; </font>
  *nonconst_cstr ='B';
  cout << nonconst_cstr << endl;
  return 0;
}
</pre>
<p>Because we casted away the constness of the string, we were able to modify the string from "A123456789" to "B1234567889".</p>
<br />
<br />


<div class="subtitle" id="reinterpret_cast">reinterpret_cast</div>
<p><strong>reinterpret_cast</strong> is intended for low-level casts that yield implementation-dependent and it would not be portable.</p>
<p>This cast is used for reinterpreting a bit pattern. It is not guaranteed to be portable. In fact, it is best to assume that <strong>reinterpret_cast</strong> is not portable at all. A typical example is an <strong>int</strong>-to-<strong>pointer</strong> to get a machine address into a program:</p>
<pre>
Register* a = reinterpret_cast&lt;Register*&gt;(0xfa);
</pre>
<p>This example is the typical use of a <strong>reinterpret_cast</strong>. We are telling the compiler that the part of memory starting with <strong>0xfa</strong> is to be considered a <strong>Register</strong>.</p>
<p>It converts any pointer type to any other pointer type, even of unrelated classes. The operation result is a simple binary copy of the value from one pointer to the other. All pointer conversions are allowed: neither the content pointed nor the pointer type itself is checked.</p>
<p>We can cast a pointer type to an integer type that's large enough to hold the pointer representation, but we can't cast a pointer to a smaller integer type or to a floating-point type. The format in which this integer value represents a pointer is platform-specific. We can't cast a function pointer to a data pointer or vice versa. </p>
<p>The syntax is:</p>
<pre>
reinterpret_cast &lt; type-name &gt; (expression)
</pre>
<p>Here is an example code:</p>
<pre>
#include &lt;iostream&gt;
using namespace std;

struct data {
	short a; 
	short b;
};

int main () {
	long value = 0xA2345678;
	data* pdata = reinterpret_cast&lt;data*&gt; (&value);
	cout << pdata->a << endl;
	return 0;
}
</pre>
<p>Output on my machine: 22136 which is 2 bytes of value.</p>
<p>Another example might be:</p>
<pre>
class A {};
class B {};

int main() 
{
	A * pA = new A;
	B * pB = reinterpret_cast&lt;B*&gt;(pA);
}
</pre>
<br />
<br />

<div class="subtitle" id="static_cast">static_cast</div>
<p><strong>static_cast</strong> can be used to force implicit conversions such as <strong>non-const</strong> object to <strong>const</strong>, <strong>int</strong> to <strong>double</strong>. It can be also be used to perform the reverse of many conversions such as <strong>void*</strong> pointers to <strong>typed</strong> pointers, <strong>base</strong> pointers to <strong>derived</strong> pointers.
But it cannot cast from <strong>const</strong> to <strong>non-const</strong> object. This can only be done by <strong>const_cast</strong> operator.</p> 
<p>The syntax is:</p>
<pre>
	static_cast &lt; type-name &gt; (expression)
</pre>
<p>It's valid only if <strong>type_name</strong> can be converted implicitly to the same type that <strong>expression</strong> has, or vise versa. Otherwise, the type cast is an error. </p>
<pre>
class Base {};
class Derived : public Base {};
class UnrelatedClass {};

int main() 
{
	Base base;
	Derived derived;

	// #1: valid upcast
	Base *pBase = static_cast&lt;Base *&gt;(&derived);  

	// #2: valid downcast
	Derived *pDerived = static_cast&lt;Derived *&gt; (&base);

	// #3: invalid, between unrelated classes
	UnrelatedClass *pUnrelated 
		= static_cast&lt;UnrelatedClass *&gt; (&derived);
}
</pre>
<p>In the example, the conversion from <strong>Base</strong> to <strong>Derived</strong> and <strong>Derived</strong> to <strong>Base</strong> are valid, but a conversion from <strong>Derived</strong> to <strong>UnrelatedClass</strong> is disallowed.</p>
<p>The #1 conversion here is valid because an upcast can be done explicitly. The #2 conversion, from a base-class pointer to a derived-class pointer, can't be done without an explicit type conversion. But because the type cast in the other direction can be made without a type cast, it's valid to use <strong>static_cast</strong> for a downcast.
However, <strong>pDerivded</strong> would point to an incomplete object of the class and could lead to runtime errors if dereferenced.</p>
<p>As we saw in the example, <strong>static_cast</strong> can perform conversions between pointers to <strong>related</strong> classes, not only from the derived class to its base, but also from a base class to its derived.</p>
<p> This ensures that at least the classes are <strong>compatible</strong> if the proper object is converted, but no safety check is performed during runtime to check if the object being converted is in fact a full object of the destination type. </p>
<p>Therefore, it is up to the programmer to ensure that the conversion is safe. On the other side, the overhead of the type-safety checks of <strong>dynamic_cast</strong> is avoided.</p>
<br />
<br />

<div class="subtitle" id="dynamic_cast">dynamic_cast</div>
<p><strong>dynamic_cast</strong> is used to perform <strong>safe downcasting</strong>, i.e., to determine whether an object is of a particular type in an inheritance hierarchy. It is the only cast that may have a significant runtime cost.</p>
<p>Look at the <a href="dynamic_cast.html">dynamic_cast</a> of C++ Tutorial - dynamic_cast.</p>




<br />
<br />

<br /><br />
<img src="images/typecast/KeumKangKaChangOri.png" alt="KeumKangKaChangOri"/>
<br /><br />


<br /><br />
<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors (Function Objects)</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL)</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="stl3_iterators.html">Standard Template Library (STL) III - Iterators</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>
<br /><br />


<br />


<br />
<br />
<br />


</div>
</div>
<div class="smallgraytext" id="footer"><a href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="#">Contact Us</a>
| Bogotobogo &copy; 2011 | <a target="_blank" href="http://www.bogotobogo.com">Bogotobogo </a>
</div>
</div>
</div>
</body>
</html>
